<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能家居控制系统</title>
    <style>
        :root {
            --primary-color: #4facfe;
            --glass-bg: rgba(255, 255, 255, 0.2);
            --glass-border: rgba(255, 255, 255, 0.3);
            --text-color: #666;
        }

        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            display: flex;
            justify-content: center;
            align-items: center;
            background: url('333.png') center/cover no-repeat fixed;
            font-family: 'Microsoft YaHei', sans-serif;
            min-height: 100vh;
        }

        .dashboard {
            width: 500px;
            background: var(--glass-bg);
            border-radius: 12px;
            backdrop-filter: blur(10px);
            border: 1px solid var(--glass-border);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin: 20px;
        }

        .title {
            font-size: 1.5em;
            text-align: center;
            color: #333;
            margin-bottom: 25px;
        }

        .control-panel {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .control-group {
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
            padding: 15px;
        }

        .control-label {
            color: #333;
            font-size: 16px;
            margin-bottom: 12px;
        }

        /* 操作模式样式 */
        .mode-container {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .mode-switch {
            position: relative;
            width: 60px;
            height: 30px;
        }

        .mode-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .mode-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .mode-slider:before {
            position: absolute;
            content: "";
            height: 22px;
            width: 22px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        .mode-switch input:checked+.mode-slider {
            background-color: var(--primary-color);
        }

        .mode-switch input:checked+.mode-slider:before {
            transform: translateX(30px);
        }

        .mode-text {
            font-size: 14px;
            color: var(--text-color);
            transition: color 0.3s;
            margin-left: 8px;
        }

        /* 其他设备样式 */
        .switch-container {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .device-switch {
            position: relative;
            width: 60px;
            height: 30px;
        }

        .device-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .device-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .device-slider:before {
            position: absolute;
            content: "";
            height: 22px;
            width: 22px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        .device-switch input:checked+.device-slider {
            background-color: var(--primary-color);
        }

        .device-switch input:checked+.device-slider:before {
            transform: translateX(30px);
        }

        .status-text {
            font-size: 14px;
            color: var(--text-color);
            transition: color 0.3s;
            margin-left: 8px;
        }

        .status-text.active {
            color: var(--primary-color);
        }

        .ac-controls {
            display: flex;
            gap: 20px;
        }

        .ac-switch {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .data-panel {
            display: grid;
            gap: 15px;
            margin-bottom: 20px;
        }

        .data-label {
            color: #666;
            font-size: 14px;
            margin-bottom: 8px;
        }

        .btn {
            width: 100%;
            height: 40px;
            background: rgba(50, 50, 50, 0.8);
            color: #f1ecec;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 16px;
            margin: 15px 0;
        }

        .btn:hover {
            background: rgba(50, 50, 50, 0.9);
        }

        input[type="text"] {
            width: 100%;
            height: 40px;
            padding: 0 10px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 5px;
            background: rgba(255, 255, 255, 0.9);
            font-size: 14px;
        }

        .nav-links {
            display: flex;
            justify-content: space-between;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid rgba(255, 255, 255, 0.2);
        }

        .nav-links a {
            color: var(--text-color);
            text-decoration: none;
            font-size: 14px;
            transition: color 0.3s;
        }

        .nav-links a:hover {
            color: #333;
        }

        .status-text.active {
            color: var(--primary-color);
        }

        /* 修改自动刷新输入框样式 */
        .refresh-interval {
            width: 100%;
            /* 改为100%宽度 */
            height: 40px;
            /* 高度与温湿度输入框一致 */
            padding: 0 10px;
            border: 1px solid rgba(0, 0, 0, 0.1);
            border-radius: 5px;
            background: rgba(255, 255, 255, 0.9);
            font-size: 14px;
        }

        /* 添加容器宽度限制 */
        .auto-refresh-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        /* 调整按钮宽度 */
        .btn-inline {
            flex: 1;
            min-width: 80px;
            /* 保持按钮最小宽度 */
        }

        /* 新增双列布局样式 */
        .row-wrapper {
            display: flex;
            gap: 20px;
            /* 元素间距 */
            justify-content: space-between;
        }

        /* 修改后的CSS样式 */
        .dual-controls {
            display: flex;
            gap: 30px;
            justify-content: flex-start;
            /* 改为左对齐 */
        }

        .control-item {
            flex: 0 1 auto;
            /* 取消固定宽度 */
        }

        .label-switch-wrapper {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            /* 关键修改：左对齐 */
            gap: 8px;
            width: 100%;
        }

        .control-label {
            text-align: left;
            /* 标签文字左对齐 */
            width: 100%;
            padding-left: 8px;
            /* 添加左间距保持视觉平衡 */
        }

        .switch-container {
            justify-content: flex-start;
            /* 开关容器左对齐 */
            padding-left: 8px;
            width: 100%;
        }
    </style>
    <script type="text/javascript">
        //新增循环上报功能
        var refreshIntervalId = null; // 存储定时器ID
        var currentInterval = 5000; // 默认刷新间隔5秒
        function init() {
            // 从本地存储获取保存的刷新间隔
            const savedInterval = localStorage.getItem('refreshInterval');
            if (savedInterval) {
                currentInterval = parseInt(savedInterval);
                document.getElementById('refreshInterval').value = currentInterval / 1000;
            }
            refresh();
            startAutoRefresh(); // 启动自动刷新
        }
        function refresh() {
            var xhr = new XMLHttpRequest(); // 创建XMLHttpRequest对象
            var temperature = document.getElementsByName("temperature");    // 定义一个数组来存储输入框元素
            var humidity = document.getElementsByName("humidity");
            var url = ""; // 请求的URL
            xhr.open("POST", url, true); // 配置请求：POST方法、URL、异步请求
            var post_req = {
                "action": "read",
                "sensors": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110],
            };
            xhr.onreadystatechange = function () {  // 监听状态变化
                if (xhr.readyState === 4 && xhr.status === 200) { // 请求完成且成功
                    var response = xhr.responseText; // 获取响应数据----------------------------------------------
                    console.log(response);
                    var info = JSON.parse(response)  //将json字符串反序列化----------------------------------------
                    console.log(info.stm32);
                    for (var i in info.stm32) {    // 遍历数组中的每个元素
                        console.log(info.stm32[i].key);
                        if (info.stm32[i].key == 101) {  // 根据key值判断数据类型
                            console.log(info.stm32[i].value);
                            document.getElementsByName('temperature')[0].value = info.stm32[i].value;  // 更新输入框的值
                        } else if (info.stm32[i].key == 102) {
                            console.log(info.stm32[i].value);
                            document.getElementsByName('humidity')[0].value = info.stm32[i].value;
                        } else if (info.stm32[i].key == 103) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifLD1_ColdOn的开关打开
                            var coldSwitch = document.getElementById('ifLD1_ColdOn');    // 获取开关元素
                            var coldStatus = document.getElementById('cold-status');    // 获取状态元素
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                coldSwitch.checked = true;     // 更新开关状态
                                coldStatus.classList.add('active'); // 添加高亮效果
                            } else {
                                coldSwitch.checked = false;
                                coldStatus.classList.remove('active');  // 移除高亮效果
                            }
                        } else if (info.stm32[i].key == 104) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifLD2_HotOn的开关打开
                            var hotSwitch = document.getElementById('ifLD2_HotOn');
                            var hotStatus = document.getElementById('hot-status');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                hotSwitch.checked = true;     // 更新开关状态
                                hotStatus.classList.add('active'); // 添加高亮效果
                            } else {
                                hotSwitch.checked = false;
                                hotStatus.classList.remove('active');  // 移除高亮效果
                            }
                        } else if (info.stm32[i].key == 105) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifFan_AirConditionOn的开关打开
                            var fanSwitch = document.getElementById('ifFan_AirConditionOn');
                            var fanStatus = document.getElementById('fan-status');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                fanSwitch.checked = true;     // 更新开关状态
                                fanStatus.classList.add('active'); // 添加高亮效果
                                fanStatus.textContent = '开启'; // 更新文字
                            } else {
                                fanSwitch.checked = false;
                                fanStatus.classList.remove('active');  // 移除高亮效果
                                fanStatus.textContent = '关闭'; // 更新文字
                            }
                        } else if (info.stm32[i].key == 106) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifFireSensorWarning的开关打开
                            var fireSwitch = document.getElementById('ifFireSensorWarning');
                            var fireStatus = document.getElementById('ifFireSensorWarning-status');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                fireSwitch.checked = true;     // 更新开关状态
                                fireStatus.classList.add('active'); // 添加高亮效果
                                fireStatus.textContent = '开启'; // 更新文字
                            } else {
                                fireSwitch.checked = false;
                                fireStatus.classList.remove('active');  // 移除高亮效果
                                fireStatus.textContent = '关闭'; // 更新文字
                            }
                        } else if (info.stm32[i].key == 107) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifBezzerAlarm的开关打开
                            var bezzerSwitch = document.getElementById('ifBezzerAlarm');
                            var bezzerStatus = document.getElementById('ifBezzerAlarm-status');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                bezzerSwitch.checked = true;     // 更新开关状态
                                bezzerStatus.classList.add('active'); // 添加高亮效果
                                bezzerStatus.textContent = '开启'; // 更新文字
                            } else {
                                bezzerSwitch.checked = false;
                                bezzerStatus.classList.remove('active');  // 移除高亮效果
                                bezzerStatus.textContent = '关闭'; // 更新文字
                            }
                        } else if (info.stm32[i].key == 108) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifPumpOn的开关打开
                            var pumpSwitch = document.getElementById('ifPumpOn');
                            var pumpStatus = document.getElementById('ifPumpOn-status');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                pumpSwitch.checked = true;     // 更新开关状态
                                pumpStatus.classList.add('active'); // 添加高亮效果
                                pumpStatus.textContent = '开启'; // 更新文字
                            } else {
                                pumpSwitch.checked = false;
                                pumpStatus.classList.remove('active');  // 移除高亮效果
                                pumpStatus.textContent = '关闭'; // 更新文字
                            }
                        } else if (info.stm32[i].key == 109) {
                            console.log("status:" + info.stm32[i].status);
                            //将ifLD3_CurtainOn的开关打开
                            var curtainSwitch = document.getElementById('ifLD3_CurtainOn');
                            var curtainStatus = document.getElementById('ifLD3_CurtainOn-status');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                curtainSwitch.checked = true;     // 更新开关状态
                                curtainStatus.classList.add('active'); // 添加高亮效果
                                curtainStatus.textContent = '开启'; // 更新文字
                            } else {
                                curtainSwitch.checked = false;
                                curtainStatus.classList.remove('active');  // 移除高亮效果
                                curtainStatus.textContent = '关闭'; // 更新文字
                            }
                        } else if (info.stm32[i].key == 110) {
                            console.log("status:" + info.stm32[i].status);
                            //将autoMode的模式切换
                            var autoModeSwitch = document.getElementById('autoMode');
                            if (info.stm32[i].status == 1) {    // 根据status值判断开关状态
                                autoModeSwitch.checked = true;     // 更新开关状态
                                updateMode(autoModeSwitch); // 更新文字
                            } else {
                                autoModeSwitch.checked = false;
                                updateMode(autoModeSwitch);  // 移除高亮效果
                            }
                        }
                    }
                }
            };
            xhr.send(JSON.stringify(post_req));
        }
        // 启动循环上报
        function startAutoRefresh() {
            // 如果已经有定时器在运行，先清除它
            if (refreshIntervalId) {
                clearInterval(refreshIntervalId);
            }
            // 设置新的定时器
            refreshIntervalId = setInterval(refresh, currentInterval);
            console.log(`循环上报已启动，间隔: ${currentInterval}毫秒`);
        }

        // 停止循环上报
        function stopAutoRefresh() {
            if (refreshIntervalId) {
                clearInterval(refreshIntervalId);
                refreshIntervalId = null;
                console.log('循环上报已停止');
            }
        }

        // 更新上报间隔
        function updateRefreshInterval() {
            const intervalInput = document.getElementById('refreshInterval');
            const seconds = parseInt(intervalInput.value);

            if (isNaN(seconds)) {
                alert('请输入有效的秒数');
                return;
            }

            if (seconds < 1) {
                alert('上报间隔不能小于1秒');
                return;
            }

            currentInterval = seconds * 1000; // 转换为毫秒
            localStorage.setItem('refreshInterval', currentInterval); // 保存到本地存储
            // 如果循环上报已经开启，则重新启动定时器
            if (refreshIntervalId) {
                startAutoRefresh();
            }

            alert(`上报间隔已设置为 ${seconds} 秒`);
        }
        // 空调控制
        // 修改后的toggleAC函数
        function toggleAC(type, element) {
            const statusElement = document.getElementById(`${type}-status`);    // 获取状态元素
            statusElement.classList.toggle('active', element.checked);

            // 确定对应的传感器键
            let sensorKey;
            switch (type) {
                case 'cold':
                    sensorKey = 103;
                    break;
                case 'hot':
                    sensorKey = 104;
                    break;
                case 'fan':
                    sensorKey = 105;
                    statusElement.textContent = element.checked ? '开启' : '关闭';
                    break;
            }

            // 构造JSON请求
            const postData = {
                action: "write",
                sensors: [sensorKey],
                values: [element.checked ? 1 : 0]
            };
            sendCommand(postData);
        }

        // 修改后的toggleDevice函数
        function toggleDevice(deviceType, element) {
            const statusElement = document.getElementById(`${deviceType}-status`);
            statusElement.textContent = element.checked ? '开启' : '关闭';
            statusElement.classList.toggle('active', element.checked);

            // 映射设备类型到传感器键
            const sensorMap = {
                'ifFireSensorWarning': 106,
                'ifBezzerAlarm': 107,
                'ifPumpOn': 100,
                'ifLD3_CurtainOn': 201
            };
            const sensorKey = sensorMap[deviceType];    // 获取传感器键

            // 构造JSON请求
            const postData = {
                action: "write",
                sensors: [sensorKey],
                values: [element.checked ? 1 : 0]
            };
            sendCommand(postData);
        }

        function updateMode(checkbox) {     //更新文字
            const modeText = document.getElementById('mode-text');
            modeText.textContent = checkbox.checked ? "自动模式" : "手动模式";
            modeText.style.color = checkbox.checked ? "var(--primary-color)" : "var(--text-color)"; // 更新文字颜色
            // 当模式切换时，发送指令
            // 发送模式切换命令（键110）
            const postData = {
                action: "write",
                sensors: [110],
                values: [checkbox.checked ? 1 : 0]  // 1表示自动模式，0表示手动模式
            };
            sendCommand(postData);
        }

        function sendCommand(data) {
            const xhr = new XMLHttpRequest();
            var url = ""; // 请求的URL
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");
            xhr.send(JSON.stringify(data));  // 发送JSON数据   
            console.log("发送指令:", data);
        }
    </script>
</head>

<!-- <body onload="init()"> 实时上报-->

<body>
    <div class="dashboard">
        <h1 class="title">智能家居控制系统</h1>
        <div class="control-panel">
            <div class="control-group">
                <div class="data-panel">
                    <div class="data-item">
                        <div class="data-label">温度</div>
                        <input type="text" name="temperature" value="0" readonly>
                    </div>

                    <div class="data-item">
                        <div class="data-label">湿度</div>
                        <input type="text" name="humidity" value="0" readonly>
                    </div>

                </div>
            </div>

            <!-- 操作模式 -->
            <div class="control-group">
                <div class="control-label">模式选择</div>
                <div class="mode-container">
                    <label class="mode-switch">
                        <input type="checkbox" id="autoMode" onchange="updateMode(this)">
                        <span class="mode-slider"></span>
                    </label>
                    <span class="mode-text" id="mode-text">手动模式</span>
                </div>
            </div>

            <!-- 空调控制 -->
            <div class="control-group">
                <div class="control-label">空调控制</div>
                <div class="ac-controls">
                    <div class="ac-switch">
                        <label class="device-switch">
                            <!-- 添加参数传递 -->
                            <input type="checkbox" id="ifLD1_ColdOn" onchange="toggleAC('cold', this)">
                            <span class="device-slider"></span>
                        </label>
                        <span class="status-text" id="cold-status">制冷</span>
                    </div>
                    <div class="ac-switch">
                        <label class="device-switch">
                            <input type="checkbox" id="ifLD2_HotOn" onchange="toggleAC('hot', this)">
                            <span class="device-slider"></span>
                        </label>
                        <span class="status-text" id="hot-status">制热</span>
                    </div>
                    <div class="ac-switch">
                        <label class="device-switch">
                            <!-- 修改type参数为'fan' -->
                            <input type="checkbox" id="ifFan_AirConditionOn" onchange="toggleAC('fan', this)">
                            <span class="device-slider"></span>
                        </label>
                        <span class="status-text" id="fan-status">关闭</span>
                    </div>
                </div>
            </div>

            <!-- 修改火焰传感器和火灾警报模块 -->
            <div class="control-group">
                <div class="dual-controls">
                    <!-- 火焰传感器 -->
                    <div class="control-item">
                        <div class="label-switch-wrapper">
                            <span class="control-label">火焰传感器</span>
                            <div class="switch-container">
                                <label class="device-switch">
                                    <input type="checkbox" id="ifFireSensorWarning"
                                        onchange="toggleDevice('ifFireSensorWarning', this)">
                                    <span class="device-slider"></span>
                                </label>
                                <span class="status-text" id="ifFireSensorWarning-status">关闭</span>
                            </div>
                        </div>
                    </div>

                    <!-- 火灾警报 -->
                    <div class="control-item">
                        <div class="label-switch-wrapper">
                            <span class="control-label">火灾警报</span>
                            <div class="switch-container">
                                <label class="device-switch">
                                    <input type="checkbox" id="ifBezzerAlarm"
                                        onchange="toggleDevice('ifBezzerAlarm', this)">
                                    <span class="device-slider"></span>
                                </label>
                                <span class="status-text" id="ifBezzerAlarm-status">关闭</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 窗帘控制 -->
            <div class="control-group">
                <div class="control-label">窗帘控制</div>
                <div class="switch-container">
                    <label class="device-switch">
                        <input type="checkbox" id="ifLD3_CurtainOn" onchange="toggleDevice('ifLD3_CurtainOn', this)">
                        <span class="device-slider"></span>
                    </label>
                    <span class="status-text" id="ifLD3_CurtainOn-status">关闭</span>
                </div>
            </div>

            <!-- 喷淋系统 -->
            <div class="control-group">
                <div class="control-label">喷淋系统</div>
                <div class="switch-container">
                    <label class="device-switch">
                        <input type="checkbox" id="ifPumpOn" onchange="toggleDevice('ifPumpOn', this)">
                        <span class="device-slider"></span>
                    </label>
                    <span class="status-text" id="ifPumpOn-status">关闭</span>
                </div>
            </div>

            <button type="button" class="btn" onclick="refresh()">数据刷新</button>
            <!-- <body onload="init()"> 循环上报:from五十块-->
                <div class="control-group auto-refresh-group">
                    <div class="control-label">状态自动刷新</div>
                    <div class="auto-refresh-controls">
                        <input type="number" 
                               id="refreshInterval" 
                               class="refresh-interval"
                               min="1" 
                               value="5"
                               placeholder="秒数">
                        <button class="btn btn-inline" onclick="updateRefreshInterval()">设置间隔</button>
                        <button class="btn btn-inline" onclick="startAutoRefresh()">开启</button>
                        <button class="btn btn-inline" onclick="stopAutoRefresh()">停止</button>
                    </div>
                </div>
            <div class="nav-links">
                <a href="mainpage.html">主页</a>
                <a href="stm32.html">STM32</a>
                <a href="modbusslave.html">Modbus Slave</a>
                <a href="modeselect.html">模式选择</a>
                <a href="http://192.168.43.241:8080/stream_simple.html">视频监控</a>
            </div>
        </div>
    </div>
</body>

</html>